﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // Get a list of serial port names.
            //string[] ports = SerialPort.GetPortNames();

            //Console.WriteLine("The following serial ports were found:");

            //// Display each port name to the console.
            //foreach (string port in ports)
            //{
            //    Console.WriteLine(port);
            //}


            var list = getDevicePortName();
            foreach (string item in list)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();

        }

        #region 新版获取 COM 内容的方法，能获取到 别名(COM*)
        private List<string> getDevicePortName()
        {
            List<string> list = new List<string>();

            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher
                ("select * from Win32_PnPEntity where Name like '%(COM%'"))
            {
                var hardInfos = searcher.Get();
                foreach (var hardInfo in hardInfos)
                {
                    if (hardInfo.Properties["Name"].Value != null)
                    {
                        string deviceName = hardInfo.Properties["Name"].Value.ToString();
                        if (string.IsNullOrEmpty(deviceName))
                            continue;
                        list.Add(deviceName);
                    }
                }
            }
            return list;
        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            var class3 = new Class3();
            class3.StartSerialPortMonitor();
        }
    }
}
